package cc.linker.steplink.crm.merchanth5.service;


import cc.linker.steplink.crm.commons.FeeConstants;
import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.enums.IntegralEnums;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.lock.LettuceLock;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.VipCustomerLogDao;
import cc.linker.steplink.crm.merchanth5.dao.VipExchangeDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.dao.integral.IntegralH5Dao;
import cc.linker.steplink.crm.merchanth5.pojo.VipCustomerLogPo;
import cc.linker.steplink.crm.merchanth5.pojo.VipPo;
import cc.linker.steplink.crm.merchanth5.pojo.coupon.CustomerCouponVo;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.merchanth5.util.MD5;
import cc.linker.steplink.crm.merchanth5.util.ParamSignUtils;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import cc.linker.steplink.crm.merchanth5.pojo.acs.ProtectPo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author huhj
 */
@Slf4j
@EnableAsync
@Service
public class VipCustomerLogService {

    @Autowired
    private VipCustomerLogDao vipCustomerLogDao;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private MallBoomService mallBoomService;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private WcPayProperties wcPayProperties;
    @Autowired
    private HttpService httpService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemProperties systemProperties;
    @Value("${wcpay.payurl}")
    private String payurl;
    @Value("${system.scrm.getwxlist}")
    private String doAddbAccountUrl;
    @Autowired
    private MerchantSalerService merchantSalerService;
    @Autowired
    private CustomerIntegralService customerIntegralService;
    @Autowired
    private IntegralH5Dao integralH5Dao;
    @Autowired
    private RequestFilter requestFilter;
    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private VipExchangeDao vipExchangeDao;
    @Autowired
    private LettuceLock lettuceLock;

    private String LUA_SCRIPT =
            "local buyNum = tonumber(ARGV[1])\n" +
                    "local goodsKey = KEYS[1]  \n" +
                    "local goodsNum = tonumber(redis.call('get',goodsKey)) \n" +
                    "if goodsNum >= buyNum \n" +
                    "then redis.call('decrby',goodsKey,buyNum) \n" +
                    "return 1 \n" +
                    "else \n" +
                    "return 0\n" +
                    "end\n" +
                    "\n" ;

    public List<VipCustomerLogPo> getVipLogList(Map<String, Object> param) throws ParseException {
        return vipCustomerLogDao.getVipLogList(param);
    }

    protected int daysBetween(Date smdate,Date bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    public void refundVip(Map<String, String> param) throws ParseException {

        VipCustomerLogPo vcpPo = this.vipLogInfo(Long.valueOf(param.get("id")));
        if(vcpPo.getVipEffectiveType() == 2){
            Date expireTime = vcpPo.getExpireTime();
            if(null!=expireTime){
                Date now = new Date();
                int days = daysBetween(now, expireTime);
                int vipEffectiveDays = vcpPo.getVipEffectiveDays();
                int reDays = Math.min(days, vipEffectiveDays);
                VipCustomerLogPo lastUnrefundVipLog = vipCustomerLogDao.getLastUnrefundVipLog(vcpPo);
                if(lastUnrefundVipLog!=null && lastUnrefundVipLog.getId()!=null){
                    if(lastUnrefundVipLog.getId() != Long.parseLong(param.get("id"))){
                        Date expireTimeLast = lastUnrefundVipLog.getExpireTime();
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(expireTimeLast);
                        calendar.add(Calendar.DAY_OF_MONTH, -reDays);
                        Date finalExpireTime = calendar.getTime();
                        lastUnrefundVipLog.setExpireTime(finalExpireTime);
                        vipCustomerLogDao.saveLog(lastUnrefundVipLog);
                    }
                }
            }
        }else{
            //退永久时退掉该权益卡所有的有效期
            vipCustomerLogDao.refundAllVip(vcpPo);
        }

        vipCustomerLogDao.refundVip(param);

        Integer isVip = this.getIsVip(vcpPo.getCustomerId(),vcpPo.getOrgId());
        if(null == isVip || 0 == isVip){
            String globalopenId = vipCustomerLogDao.getGlobalopenIdByCustomerId(vcpPo.getCustomerId());
            if(StringUtils.isEmpty(globalopenId)){
                globalopenId = vipCustomerLogDao.getAppUserIdByCustomerId(vcpPo.getCustomerId());
            }
            String key = MD5.encode(param.get("orgId") + globalopenId);
            String h5User = stringRedisTemplate.opsForValue().get("login:" + key);
            if(!StringUtils.isEmpty(h5User)){
                WxUser wxUser = JSON.parseObject(h5User, WxUser.class);
                wxUser.setIsVip(0);
                h5User = JSON.toJSONString(wxUser);
                stringRedisTemplate.opsForValue().set("login:" + key, h5User, 15, TimeUnit.MINUTES);
            }
            List<String> appUserIdList = vipCustomerLogDao.getappUserIdByCustomerId(vcpPo.getCustomerId());
            if(appUserIdList!=null && appUserIdList.size()>0){
                for(String appUserId : appUserIdList){
                    String appKey = MD5.encode(param.get("orgId") + appUserId);
                    String appUser = stringRedisTemplate.opsForValue().get("login:" + appKey);
                    if(!StringUtils.isEmpty(appUser)){
                        WxUser wxUser = JSON.parseObject(appUser, WxUser.class);
                        wxUser.setIsVip(0);
                        appUser = JSON.toJSONString(wxUser);
                        stringRedisTemplate.opsForValue().set("login:" + appKey, appUser, 15, TimeUnit.MINUTES);
                    }
                }
            }
        }
    }

    public Integer getIsVip(String customerId,String orgId) {
        Integer isVip = vipCustomerLogDao.getIsVip(customerId);
        if(isVip==null || isVip == 0){
            Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customerId,orgId);
            int customerGrowthScore = Integer.valueOf(integralCustomerInfo.get("customerGrowthScore").toString());
            Integer isVipLevel = vipCustomerLogDao.getIsVipLevel(customerGrowthScore,orgId);
            if(isVipLevel!=null && isVipLevel>0){
                isVip=1;
            }
        }
        if(isVip==null || isVip == 0){
            isVip = vipCustomerLogDao.getIsVipByApp(customerId);
        }
        return  isVip==null?0:isVip;
    }

    public List<VipPo> getViplist(Map<String, Object> param) {
        return vipCustomerLogDao.getViplist(param);
    }

    public VipPo vipInfo(Map<String, Object> param) {
        VipPo vipInfo = vipCustomerLogDao.vipInfo(param);

        if(vipInfo!=null){
            vipInfo.setIsFull(0);
            if(vipInfo.getLimitNum()>0){
                String limitKey = "{vip}vip:limit_num_"+vipInfo.getId();
                String limit = stringRedisTemplate.opsForValue().get(limitKey);
                if(!StringUtils.isEmpty(limit) && Integer.valueOf(limit)<1){
                    vipInfo.setIsFull(1);
                }
                int openCount = vipCustomerLogDao.getVipOpenCount(vipInfo.getId());
                if (openCount >= vipInfo.getLimitNum()) {
                    vipInfo.setIsFull(1);
                }
            }

            param.put("vipId",vipInfo.getId());
            //会员权益
            List<Map<String,Object>> vipRightList = vipCustomerLogDao.getVipRightList(vipInfo.getId());
            vipInfo.setVipRightList(vipRightList);
            //权益卡-礼包-卡券
            List<Map<String,Object>> vipCoupons = vipCustomerLogDao.getVipCoupons(vipInfo.getId().toString());
            if(null!=vipCoupons && vipCoupons.size()>0 && vipInfo.getIsCoupon() == 1){
//                HttpServletRequest request = (HttpServletRequest)param.get("request");
//                CouponCustomerInfo couponCustomerInfo = requestFilter.getCouponCustomerInfo(request);
                CouponCustomerInfo couponCustomerInfo = CouponCustomerInfo
                        .builder()
                        .customerId(param.get("customerId").toString())
                        .cover("")
                        .customerName("")
                        .orgId(vipInfo.getOrgId())
                        .build();


                for (int i = vipCoupons.size()-1; i >= 0; i--) {
                    Map<String,Object> res = (Map)couponRequest.doRequest("coupon-detail", vipCoupons.get(i), couponCustomerInfo);
                    if(null == res || null == res.get("name")){
                        vipCoupons.remove(i);
                    }else{
                        vipCoupons.get(i).put("name", res.get("name"));
                        vipCoupons.get(i).put("cover",res.get("cover"));
                    }
                }

//
//                for(Map<String,Object> vipCoupon:vipCoupons){
//                    Map<String, Object> res = (Map) couponRequest.doRequest("coupon-detail", vipCoupon, couponCustomerInfo);
//                    vipCoupon.put("cover",res.get("cover"));
//                    vipCoupon.put("name",res.get("name"));
//                }
                vipInfo.setVipCouponList(vipCoupons);
            }

            if(vipInfo.getIsOpen()!=null && vipInfo.getIsOpen()==1){
                //查询
                VipPo vipInfo2 = vipCustomerLogDao.vipInfoByOpen(param);
                if (null != vipInfo2) {
                    vipInfo.setCardId(vipInfo2.getCardId());
                    Integer effectiveType = vipInfo2.getEffectiveType();
                    if (StringUtils.isEmpty(vipInfo2.getExpireDay()) || effectiveType == 1) {
                        vipInfo.setExpireDay("永久");
                    } else {
                        vipInfo.setExpireDay(vipInfo2.getExpireDay());
                    }
                    vipInfo.setEffectiveType(effectiveType);
                    vipInfo.setCreateTime(vipInfo2.getCreateTime());
                }
            }
            return vipInfo;
        }else{
            throw GlobalException.notFound();
        }
    }

    public VipCustomerLogPo vipLogInfo(Long id) {
        return vipCustomerLogDao.vipLogInfo(id);
    }

    public VipCustomerLogPo vipLogInfoByOrderSn(String orderSn) {
        return vipCustomerLogDao.vipLogInfoByOrderSn(orderSn);
    }

    /**
     * 根据商品id新增会员
     */
    @Async
    public void openVipByGoodsId(String goodsId,String customerId,String orgId,Integer payMode,String goodsName){
        //根据商品id查出会员卡
        List<Long> vipIds = vipCustomerLogDao.getVipIdsByGoodsId(goodsId);
        if(vipIds!=null && vipIds.size()>0){
            for(Long vipId : vipIds){
                try{
                    this.open(null,customerId,vipId,orgId,payMode,null,goodsName);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

    }


    public VipCustomerLogPo exchangeVip(Map<String, Object> params, String customerId, String phone, String orgId,Integer payMode) {

        //根据exchangeCode查询
        if(StringUtils.isEmpty(params.get("exchangeCode"))){
            throw GlobalException.build("兑换码无效");
        }
        String lockKey = "exchangeCode:exchangeCode_" + params.get("exchangeCode").toString();
        String requestId = UUID.randomUUID().toString();
        boolean lock = lettuceLock.tryLock(lockKey,requestId,2,TimeUnit.MINUTES);
        if (!lock) {
            throw GlobalException.build("该兑换码正在兑换中!");
        }
        try {
            Map exchangeCodeMap = vipExchangeDao.getExchangeCodeValue(params);
            if(exchangeCodeMap==null){
                throw GlobalException.build("兑换码无效");
            }
            String exchangePhone = "";
            String startTimeString = "";
            String endTimeString = "";
            String vipId = "";
            Integer exchangeDays = 0;
            Integer exchangeStatus = 1;
            Integer status = 0;
            Integer isDelete = 0;
            if(!StringUtils.isEmpty(exchangeCodeMap.get("isDelete"))){
                isDelete = Integer.valueOf(exchangeCodeMap.get("isDelete").toString());
            }
            if(!StringUtils.isEmpty(exchangeCodeMap.get("exchangePhone"))){
                exchangePhone = exchangeCodeMap.get("exchangePhone").toString();
            }
            if(!StringUtils.isEmpty(exchangeCodeMap.get("startTime"))){
                startTimeString = exchangeCodeMap.get("startTime").toString();
            }
            if(!StringUtils.isEmpty(exchangeCodeMap.get("endTime"))){
                endTimeString = exchangeCodeMap.get("endTime").toString();
            }
            if(!StringUtils.isEmpty(exchangeCodeMap.get("relateId"))){
                vipId = exchangeCodeMap.get("relateId").toString();
            }
            if(!StringUtils.isEmpty(exchangeCodeMap.get("exchangeDays"))){
                exchangeDays = Integer.valueOf(exchangeCodeMap.get("exchangeDays").toString());
            }
            if(!StringUtils.isEmpty(exchangeCodeMap.get("exchangeStatus"))){
                exchangeStatus = Integer.valueOf(exchangeCodeMap.get("exchangeStatus").toString());
            }
            if(!StringUtils.isEmpty(exchangeCodeMap.get("status"))){
                status = Integer.valueOf(exchangeCodeMap.get("status").toString());
            }
            if(isDelete==1){
                throw GlobalException.build("活动异常");
            }
            if(!StringUtils.isEmpty(exchangePhone) && !exchangePhone.equals(phone)){
                throw GlobalException.build("兑换码无效");
            }
            if(exchangeStatus==1){
                throw GlobalException.build("兑换码已被兑换");
            }
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date startTime=null;
            Date endTime=null;
            Date nowTime;
            try {
                Date now =  new Date();
                String nowString = formatter.format(now);
                if(!StringUtils.isEmpty(startTimeString)){
                    startTime = formatter.parse(startTimeString);
                }
                if(!StringUtils.isEmpty(endTimeString)){
                    endTime = formatter.parse(endTimeString);
                }
                nowTime = formatter.parse(nowString);
            }catch (Exception e){
                e.printStackTrace();
                throw GlobalException.build("兑换码无效");
            }
            if(startTime!=null && nowTime.before(startTime)){
                throw GlobalException.build("活动未开始");
            }
            if(endTime!=null && nowTime.after(endTime)){
                throw GlobalException.build("活动已过期");
            }
            if(status==0){
                throw GlobalException.build("活动暂停，请稍后试试");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("customerId", customerId);
            param.put("id", vipId);
            VipPo vipPo = this.vipInfo(param);
            if (vipPo == null) {
                throw GlobalException.build("活动异常");
            }
            //修改兑换状态
            vipExchangeDao.updateExchangeStatus(params);
            boolean isOpen = false;//是否是开通状态
            if(vipPo.getIsOpen()==1){
                isOpen = true;
            }
            //根据权益卡id产生用户权益卡编号
            String cardIdKey = "vip:card_id_"+vipId;
            String cardIdFinal = "";
            //到期时间
            Date oldExpireTime = new Date();
            Integer isForever = 0;
            if(!isOpen){
                //首开
                String cardIdStr = stringRedisTemplate.opsForValue().get(cardIdKey);
                int cardId = 1;
                if(!StringUtils.isEmpty(cardIdStr)){
                    cardId = Integer.parseInt(cardIdStr);
                }else{
                    stringRedisTemplate.opsForValue().increment(cardIdKey,1);
                }
                NumberFormat formatters = NumberFormat.getNumberInstance();
                formatters.setMinimumIntegerDigits(6);
                formatters.setGroupingUsed(false);
                cardIdFinal = formatters.format(cardId);
            }else{
                //续费
                Map<String, Object> lastVipLog = vipCustomerLogDao.getLastVipLog(Long.valueOf(vipId), customerId);
                if(null!=lastVipLog){
                    if(!StringUtils.isEmpty(lastVipLog.get("cardId"))){
                        cardIdFinal = lastVipLog.get("cardId").toString();
                    }
                    if(!StringUtils.isEmpty(lastVipLog.get("expireTime"))){
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try {
                            oldExpireTime = simpleDateFormat.parse(lastVipLog.get("expireTime").toString());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }else {
                        isForever = 1;
                    }
                }
            }

            Integer effectiveDays = exchangeDays;
            String vipTypeDesc = "兑换码兑换"+effectiveDays+"天";
            Integer effectiveType = 2;
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DAY_OF_MONTH, effectiveDays);
            Date expireTime = c.getTime();
            String orderSn = TransactionOrderUtil.TYPE_VIP + TransactionOrderUtil.getPrimaryKey();
            VipCustomerLogPo vipLog = new VipCustomerLogPo();
            vipLog.setCardId(cardIdFinal);
            vipLog.setCustomerId(customerId);
            vipLog.setOrgId(orgId);
            vipLog.setVipId(Long.valueOf(vipId));
            vipLog.setVipName(vipPo.getName());
            vipLog.setVipImage(vipPo.getImage());
            vipLog.setVipBgImage(vipPo.getBgImage());
            vipLog.setVipType(5);//兑换码兑换
            vipLog.setVipTypeDesc(vipTypeDesc);
            vipLog.setVipEffectiveType(effectiveType);//自定义
            vipLog.setVipEffectiveDays(effectiveDays);
            vipLog.setVipTip(vipPo.getTip());
            vipLog.setExchangeId(exchangeCodeMap.get("exchangeId").toString());
            vipLog.setExchangeCode(exchangeCodeMap.get("exchangeCode").toString());
            vipLog.setPaymentState(1);
            String vipBenefit = "";
            List<Map<String, Object>> levelRights = vipPo.getVipRightList();
            if(levelRights!=null && levelRights.size()>0){
                List<String> vipBenefits = new ArrayList<>();
                if(levelRights.size()>0){
                    for (Map<String, Object> lr : levelRights) {
                        if(!StringUtils.isEmpty(lr.get("type"))){
                            vipBenefits.add(lr.get("type").toString());
                        }
                    }
                }
                if(vipBenefits.size()>0){
                    vipBenefit = vipBenefits.stream().collect(Collectors.joining(","));
                }
            }
            vipPo.setBenefit(vipBenefit);
            vipLog.setVipBenefit(vipBenefit);

            //延长有效期
            if(isOpen){
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(oldExpireTime);
                calendar.add(Calendar.DAY_OF_MONTH, effectiveDays);//增加日
                expireTime = calendar.getTime();
            }
            if(isForever==1){
                vipLog.setVipEffectiveType(1);
                expireTime = null;
            }
            vipLog.setExpireTime(expireTime);
            vipLog.setStatus(1);
            vipLog.setOrderSn(orderSn);
            this.addLog(vipLog);
            if(!isOpen){
                stringRedisTemplate.opsForValue().increment(cardIdKey,1);
            }
            stringRedisTemplate.opsForValue().set("orderType_"+orderSn,"5",1, TimeUnit.HOURS);
            if(!StringUtils.isEmpty(vipPo.getBenefit())){
                this.openBenefit(vipPo.getBenefit(),orgId,customerId,payMode);
            }
            if((vipPo.getGiftsGrowth()!=null && vipPo.getGiftsGrowth()>0) || (vipPo.getGiftsIntegral()!=null && vipPo.getGiftsIntegral()>0) || vipPo.getIsCoupon() == 1) {
                Integer giftsGrowth = 0;
                if (vipPo.getGiftsGrowth() != null) {
                    giftsGrowth = vipPo.getGiftsGrowth();
                }
                Integer giftsIntegral = 0;
                if (vipPo.getGiftsIntegral() != null) {
                    giftsIntegral = vipPo.getGiftsIntegral();
                }
                //礼包
                this.addGifts(giftsGrowth, giftsIntegral, customerId, 1, orgId, "", vipId.toString());
            }
            return vipLog;
        }finally {
            // 解锁
            lettuceLock.releaseLock(lockKey,requestId);
        }
    }

    public Map<String,Object> open(Map<String,Object> params,String customerId,Long vipId,String orgId,Integer payMode,String openId,String goodsName){
        Map<String, Object> param = new HashMap<>();
        param.put("customerId", customerId);
        param.put("id", vipId);
        VipPo vipPo = this.vipInfo(param);
        if(!"-1".equals(openId)){//openid=-1表示管理员赠送
            if (vipPo == null || vipPo.getStatus()!=1) {
                throw GlobalException.build("该会员卡未发卡！");
            }
        }
        int type = vipPo.getType();

        boolean isOpen = false;//是否是开通状态
        if (vipPo.getIsOpen() == 1) {
            if (type == 3 && !"-1".equals(openId)) {
                //已经开通的不用开通（目前的需求是这样）
                Map<String, Object> map = new HashMap<>();
                map.put("status", -4);
                return map;
            }
            isOpen = true;
        }

        //开启限购（仅对首开有效）
        if(vipPo.getLimitNum()>0 && !isOpen && !"-1".equals(openId)){
            String limitKey = "{vip}vip:limit_num_"+vipId.toString();
            String limit = stringRedisTemplate.opsForValue().get(limitKey);
            if(!StringUtils.isEmpty(limit)){
                if(Integer.parseInt(limit)<0){
                    throw GlobalException.build("达到上限");
                }
                DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_SCRIPT,Long.class);
                Long limitResult = stringRedisTemplate.execute(redisScript, Collections.singletonList(limitKey),"1");
                if (null == limitResult || limitResult < 1) {
                    throw GlobalException.build("达到上限");
                }
            }
        }

        //根据权益卡id产生用户权益卡编号
        String cardIdKey = "vip:card_id_"+vipId;
        String cardIdFinal = "";
        //到期时间
        Date oldExpireTime = new Date();
        if(!isOpen){
            //首开
            String cardIdStr = stringRedisTemplate.opsForValue().get(cardIdKey);
            int cardId = 1;
            if(!StringUtils.isEmpty(cardIdStr)){
                cardId = Integer.parseInt(cardIdStr);
            }else{
                stringRedisTemplate.opsForValue().increment(cardIdKey,1);
            }
            NumberFormat formatter = NumberFormat.getNumberInstance();
            formatter.setMinimumIntegerDigits(6);
            formatter.setGroupingUsed(false);
            cardIdFinal = formatter.format(cardId);
        }else{
            //续费
            Map<String, Object> lastVipLog = vipCustomerLogDao.getLastVipLog(vipId, customerId);
            if(null!=lastVipLog){
                if(!StringUtils.isEmpty(lastVipLog.get("cardId"))){
                    cardIdFinal = lastVipLog.get("cardId").toString();
                }
                if(!StringUtils.isEmpty(lastVipLog.get("expireTime"))){
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        oldExpireTime = simpleDateFormat.parse(lastVipLog.get("expireTime").toString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        Integer effectiveDays = 0;
        int effectiveMonth = 0;
        String amountString = "";
        String monthString ="";
        int amount =0;
        Date expireTime = null;
        String optionId = "";
        if (type == 2 && params != null) {
            if(StringUtils.isEmpty(params.get("optionId"))){
                throw GlobalException.build("参数错误");
            }
            optionId = params.get("optionId").toString();
            String options  = vipPo.getOptions();
            List<Map> optionsMapList = JSON.parseObject(options,  List.class);
            for(Map optionsMap : optionsMapList){
                if(optionId.equals(optionsMap.get("optionId").toString())){
                    amountString = optionsMap.get("amount").toString();
                    monthString = optionsMap.get("month").toString();
                    double amountY = (Double.parseDouble(amountString))*100;
                    amount = (int) amountY;
                    int month = Integer.parseInt(monthString);
                    effectiveMonth = month;
                    Date date = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.MONTH, month);//增加月
                    expireTime = calendar.getTime();
                    //计算两个日期相差的天数
                    long intervalMilli = expireTime.getTime() - date.getTime();
                    effectiveDays = (int) (intervalMilli / (24 * 60 * 60 * 1000));
                }
            }
        }else {
            if(vipPo.getEffectiveDays()!=null && vipPo.getEffectiveType()!=null && vipPo.getEffectiveType()!=1){
                effectiveDays = vipPo.getEffectiveDays();
            }
        }
        Integer effectiveType = vipPo.getEffectiveType();
        if(effectiveDays!=null && effectiveDays>0){
            effectiveType = 2;
        }
        if(effectiveType == 2 && "-1".equals(openId) && StringUtils.isEmpty(optionId)){
            VipPo vipInfoPo = vipCustomerLogDao.vipBaseInfo(param);
            effectiveType = vipInfoPo.getEffectiveType();
        }
        String vipTypeDesc = "直接领取";
        if (type == 2) {
            vipTypeDesc = "付费购买" + effectiveMonth + "个月" + amountString + "元";
            if(isOpen){
                vipTypeDesc = "续费" + effectiveMonth + "个月" + amountString + "元";
            }
        }else if (type == 3){
            vipTypeDesc = "购买商品"+goodsName;
        }

        if ("-1".equals(openId)){
            vipTypeDesc = "后台赠送";
            type = 11;
            if(effectiveMonth>0){
                vipTypeDesc = vipTypeDesc + effectiveMonth + "个月";
            }else if(effectiveDays>0){
                vipTypeDesc = vipTypeDesc + effectiveDays + "天";
            }
        }

        if(expireTime==null && effectiveDays>0){
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DAY_OF_MONTH, effectiveDays);
            expireTime = c.getTime();
        }

        //B用户付钱，A用户受益
        String orderSn = TransactionOrderUtil.TYPE_VIP + TransactionOrderUtil.getPrimaryKey();
        VipCustomerLogPo vipLog = new VipCustomerLogPo();
        vipLog.setCardId(cardIdFinal);
        vipLog.setCustomerId(customerId);
        vipLog.setOrgId(orgId);
        vipLog.setVipId(vipId);
        vipLog.setVipName(vipPo.getName());
        vipLog.setVipImage(vipPo.getImage());
        vipLog.setVipBgImage(vipPo.getBgImage());
        vipLog.setVipType(type);
        vipLog.setVipTypeDesc(vipTypeDesc);
        vipLog.setVipEffectiveType(effectiveType);
        vipLog.setVipEffectiveDays(effectiveDays);
        vipLog.setVipTip(vipPo.getTip());
        String shareCustomerId = "";
        if(params!=null && params.containsKey("shareCustomerId") && !StringUtils.isEmpty(params.get("shareCustomerId"))){
            shareCustomerId = (String)  params.get("shareCustomerId");
        }
        vipLog.setShareCustomerId(shareCustomerId);
        String vipBenefit = "";
        List<Map<String, Object>> levelRights = vipPo.getVipRightList();
        if(levelRights!=null && levelRights.size()>0){
            List<String> vipBenefits = new ArrayList<>();
            for (Map<String, Object> lr : levelRights) {
                if(!StringUtils.isEmpty(lr.get("type"))){
                    vipBenefits.add(lr.get("type").toString());
                }
            }
            if(vipBenefits.size()>0){
                vipBenefit = String.join(",", vipBenefits);
            }
        }
        vipPo.setBenefit(vipBenefit);
        vipLog.setVipBenefit(vipBenefit);

        //延长有效期---续费
        if(isOpen && effectiveMonth>0){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(oldExpireTime);
            calendar.add(Calendar.MONTH, effectiveMonth);//增加月
            expireTime = calendar.getTime();
        }

        //延长有效期---赠送
        if(isOpen && "-1".equals(openId) && vipPo.getEffectiveType() == 2 && vipPo.getEffectiveDays()>0){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(oldExpireTime);
            calendar.add(Calendar.DAY_OF_MONTH, vipPo.getEffectiveDays());
            expireTime = calendar.getTime();
        }

        vipLog.setExpireTime(expireTime);
        vipLog.setStatus(1);
        if(effectiveMonth>0){
            vipLog.setVipEffectiveMonth(effectiveMonth);
        }
        if(amount>0 && !"-1".equals(openId)){
            vipLog.setAmount(amount);
            vipLog.setPayType(payMode);
        }
        vipLog.setOrderSn(orderSn);
        if(amount>0 && !"-1".equals(openId)){
            vipLog.setPaymentState(0);
        }else{
            vipLog.setPaymentState(1);
        }
        this.addLog(vipLog);
        if(!isOpen){
            stringRedisTemplate.opsForValue().increment(cardIdKey,1);
        }
        stringRedisTemplate.opsForValue().set("orderType_"+orderSn,"5",1, TimeUnit.HOURS);
        if(amount>0 && !"-1".equals(openId)){
            String orderSource = "";
            if(!StringUtils.isEmpty(params.get("orderSource"))){
                orderSource = params.get("orderSource").toString();
            }
            String frontUrl = "";
            if(!StringUtils.isEmpty(params.get("frontUrl"))){
                frontUrl = params.get("frontUrl").toString();
            }
            return this.pay(payMode,openId,orderSource,orgId,amount,orderSn,customerId,frontUrl,vipLog.getShareCustomerId(),vipId);
        }else {
            if(!StringUtils.isEmpty(vipPo.getBenefit())){
                this.openBenefit(vipPo.getBenefit(),orgId,customerId,payMode);
            }
            if((vipPo.getGiftsGrowth()!=null && vipPo.getGiftsGrowth()>0) || (vipPo.getGiftsIntegral()!=null && vipPo.getGiftsIntegral()>0) || vipPo.getIsCoupon() == 1){
                Integer giftsGrowth = 0;
                if(vipPo.getGiftsGrowth()!=null){
                    giftsGrowth = vipPo.getGiftsGrowth();
                }
                Integer giftsIntegral = 0;
                if(vipPo.getGiftsIntegral()!=null){
                    giftsIntegral = vipPo.getGiftsIntegral();
                }
                //礼包
                this.addGifts(giftsGrowth,giftsIntegral,customerId,1,orgId,"",vipId.toString());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("status", -2);
            map.put("orderSn", orderSn);
            map.put("effectiveDays", effectiveDays);
            map.put("effectiveMonth", effectiveMonth);
            map.put("effectiveType", effectiveType);
            map.put("name", vipPo.getName());
            return map;
        }
    }

    public Map integralOpen(Map params,String customerId,Long vipId,String orgId,Integer payMode,String openId){
        Long integralVipId = vipId;
        Map<String, Object> param = new HashMap<>();
        param.put("customerId", customerId);
        param.put("id", vipId);
        param.put("orgId", orgId);
        Map<String, Object> integralVipInfo = vipCustomerLogDao.getIntegralVipInfo(param);
        if(null == integralVipInfo){
            throw GlobalException.build("参数错误");
        }
        if("1".equals(integralVipInfo.get("isDelete").toString())){
            throw GlobalException.build("该权益卡已失效，请选择其他权益卡");
        }
        if(!"1".equals(integralVipInfo.get("goodsStatus").toString())){
            throw GlobalException.build("该权益卡未上架，请选择其他权益卡");
        }
        String optionId = params.get("optionId").toString();
        String options  = integralVipInfo.get("options").toString();
        //判断用户积分
        Map<String, Object> integralCustomerInfo = customerIntegralService.getIntegralCustomerInfo(customerId,orgId);
        Long currentGrowthScore = 0L;
        Long currentScore = 0L;
        if(integralCustomerInfo!=null && !StringUtils.isEmpty(integralCustomerInfo.get("customerGrowthScore"))){
            currentGrowthScore = Long.valueOf(integralCustomerInfo.get("customerGrowthScore").toString());
            currentScore = Long.valueOf(integralCustomerInfo.get("customerScore").toString());
        }

        //等级限制
        Integer levelOrder =0;
        List<Map<String, Object>> levels = integralH5Dao.listLevels(param);
        if(levels.size()>0) {
            //获取最后一个等级
            Map<String, Object> endLevel = levels.get(levels.size()-1);
            //如果用户当前等级大于最后一个等级的经验值则当前等级就是最后一个等级
            if(currentGrowthScore>= (Long) endLevel.get("levelScore")) {
                levelOrder = (Integer) endLevel.get("levelOrder");
            }else{
                //如果不是最后一个等级，遍历所有找到对应的当前等级
                for (int i = 0; i <= levels.size()-1; i++) {
                    Map<String, Object> level = levels.get(i);
                    //获取当前等级数据
                    if ((Long) level.get("levelScore") > currentGrowthScore) {
                        if (i != 0) {
                            levelOrder = (Integer) levels.get(i - 1).get("levelOrder");
                        }
                        break;
                    }
                }
            }
        }
        int quotaLevel = Integer.valueOf(integralVipInfo.get("quotaLevel").toString());
//        Integer level = vipCustomerLogDao.getCustomerLevel(customerId);
        if(quotaLevel>levelOrder){
            throw GlobalException.build("等级不够，无法兑换");
        }
        Integer integral = 0;
        param.put("id",integralVipInfo.get("originalGoodsId"));
        VipPo vipPo = this.vipInfo(param);
//        if (vipPo == null || vipPo.getStatus()!=1) {
//            throw GlobalException.build("该会员卡未发卡！");
//        }
        int type = 4;
        if(vipPo.getIsOpen()==1){
            //已经开通的不用开通（目前的需求是这样）
            Map<String, Object> map = new HashMap<>();
            map.put("status", -4);
            return map;
        }
        vipId = Long.valueOf(integralVipInfo.get("originalGoodsId").toString());
        //根据权益卡id产生用户权益卡编号
        String cardIdKey = "vip:card_id_"+vipId;
        String cardIdStr = stringRedisTemplate.opsForValue().get(cardIdKey);
        int cardId = 1;
        if(!StringUtils.isEmpty(cardIdStr)){
            cardId = Integer.valueOf(cardIdStr);
        }else{
            stringRedisTemplate.opsForValue().increment(cardIdKey,1);
        }
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMinimumIntegerDigits(6);
        formatter.setGroupingUsed(false);
        String cardIdFinal = formatter.format(cardId);

        Integer effectiveDays = 0;
        Integer effectiveMonth = 0;
        String amountString = "";
        String monthString = "";
        Integer amount = 0;
        Integer goodsCount = 0;
        Date expireTime = null;
        if(StringUtils.isEmpty(params.get("optionId"))){
            throw GlobalException.build("参数错误");
        }
        List<Map> optionsMapList = JSON.parseObject(options,  List.class);
        for(Map optionsMap : optionsMapList){
            if(optionId.equals(optionsMap.get("optionId").toString())){
                amountString = optionsMap.get("amount").toString();
                if(!StringUtils.isEmpty(amountString)){
                    BigDecimal d = new BigDecimal(100);
                    amount = new BigDecimal(amountString).multiply(d).intValue();
                }
                monthString = optionsMap.get("month").toString();
                integral = Integer.valueOf(optionsMap.get("integral").toString());
                if(currentScore<integral){
                    throw GlobalException.build("积分不足");
                }
                goodsCount = Integer.valueOf(optionsMap.get("goodsCount").toString());
                if(goodsCount<1){
                    throw GlobalException.build("名额已满");
                }
                optionsMap.put("goodsCount",goodsCount-1);
                Integer month = Integer.valueOf(monthString);
                effectiveMonth = month;
                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.MONTH, month);//增加月
                expireTime = calendar.getTime();
                //计算两个日期相差的天数
                long intervalMilli = expireTime.getTime() - date.getTime();
                effectiveDays = (int) (intervalMilli / (24 * 60 * 60 * 1000));
            }
        }
        Integer effectiveType = vipPo.getEffectiveType();
        if(effectiveDays>0){
            effectiveType = 2;
        }

        String vipTypeDesc = "积分兑换"+monthString+"个月";
//        String vipTypeDesc = "积分兑换"+monthString+"个月"+integral+"积分"+ NumberUtils.fenToYuan(Long.valueOf(amount)) +"元";
//        if(expireTime==null && effectiveDays>0){
//            Calendar c = Calendar.getInstance();
//            c.add(Calendar.DAY_OF_MONTH, effectiveDays);
//            expireTime = c.getTime();
//        }
        //B用户付钱，A用户受益
        String orderSn = TransactionOrderUtil.TYPE_VIP + TransactionOrderUtil.getPrimaryKey();
        VipCustomerLogPo vipLog = new VipCustomerLogPo();
        vipLog.setIntegral(integral);
        vipLog.setCardId(cardIdFinal);
        vipLog.setCustomerId(customerId);
        vipLog.setOrgId(orgId);
        vipLog.setVipId(vipId);
        vipLog.setVipName(vipPo.getName());
        vipLog.setVipImage(vipPo.getImage());
        vipLog.setVipBgImage(vipPo.getBgImage());
        vipLog.setVipType(type);
        vipLog.setVipTypeDesc(vipTypeDesc);
        vipLog.setVipEffectiveType(effectiveType);
        vipLog.setVipEffectiveDays(effectiveDays);
        vipLog.setVipTip(vipPo.getTip());
        String vipBenefit = "";
        List<Map<String, Object>> levelRights = vipPo.getVipRightList();
        if(levelRights!=null && levelRights.size()>0){
            List<String> vipBenefits = new ArrayList<>();
            if(levelRights.size()>0){
                for (Map<String, Object> lr : levelRights) {
                    if(!StringUtils.isEmpty(lr.get("type"))){
                        vipBenefits.add(lr.get("type").toString());
                    }
                }
            }
            if(vipBenefits.size()>0){
                vipBenefit = vipBenefits.stream().collect(Collectors.joining(","));
            }
        }
        vipPo.setBenefit(vipBenefit);
        vipLog.setVipBenefit(vipBenefit);
        vipLog.setExpireTime(expireTime);
        vipLog.setStatus(1);
        if(effectiveMonth>0){
            vipLog.setVipEffectiveMonth(effectiveMonth);
        }
        if(amount>0){
            vipLog.setAmount(amount);
            vipLog.setPayType(payMode);
        }
        vipLog.setOrderSn(orderSn);
        vipLog.setIntegralVipId(integralVipId);
        vipLog.setIntegralOptionId(Long.valueOf(optionId));
        if(amount>0){
            vipLog.setPaymentState(0);
        }else{
            vipLog.setPaymentState(1);
            vipCustomerLogDao.addSaleNum(integralVipId);
        }
        String shareCustomerId = "";
        if(params!=null && params.containsKey("shareCustomerId") && !StringUtils.isEmpty(params.get("shareCustomerId"))){
            shareCustomerId = (String)  params.get("shareCustomerId");
        }
        vipLog.setShareCustomerId(shareCustomerId);
        this.addLog(vipLog);
        //扣除积分
        customerIntegralService.addIntegralCustomerLog(customerId,"兑换权益卡", IntegralEnums.customerScore.toString(),"-"+integral.toString(),IntegralEnums.other.toString(),orgId);
        //增加日志
        Map<String, Object> log = new HashMap<String, Object>();
        log.put("logId", UUID.randomUUID().toString());
        log.put("customerId", customerId);
        log.put("scoreValue", "-"+integral);
        log.put("scoreType", 6);
        log.put("actionRemark", "兑换"+vipPo.getName()+",订单号："+orderSn+",扣除"+integral+"积分");
        integralH5Dao.addIntegralLog(log);
        stringRedisTemplate.opsForValue().increment(cardIdKey,1);
        stringRedisTemplate.opsForValue().set("orderType_"+orderSn,"5",1, TimeUnit.HOURS);
        if(amount>0){
            String orderSource = "";
            if(!StringUtils.isEmpty(params.get("orderSource"))){
                orderSource = params.get("orderSource").toString();
            }
            String frontUrl = "";
            if(!StringUtils.isEmpty(params.get("frontUrl"))){
                frontUrl = params.get("frontUrl").toString();
            }
            return this.pay(payMode,openId,orderSource,orgId,amount,orderSn,customerId,frontUrl,vipLog.getShareCustomerId(),vipId);
        }else {
            if(!StringUtils.isEmpty(vipPo.getBenefit())){
                this.openBenefit(vipPo.getBenefit(),orgId,customerId,payMode);
            }
            if((vipPo.getGiftsGrowth()!=null && vipPo.getGiftsGrowth()>0) || (vipPo.getGiftsIntegral()!=null && vipPo.getGiftsIntegral()>0) || vipPo.getIsCoupon() == 1){
                Integer giftsGrowth = 0;
                if(vipPo.getGiftsGrowth()!=null){
                    giftsGrowth = vipPo.getGiftsGrowth();
                }
                Integer giftsIntegral = 0;
                if(vipPo.getGiftsIntegral()!=null){
                    giftsIntegral = vipPo.getGiftsIntegral();
                }
                //礼包
                this.addGifts(giftsGrowth,giftsIntegral,customerId,1,orgId,"",vipId.toString());
            }
//            vipCustomerLogDao.addSaleNum(integralVipId);
            Map<String ,Object> tmp = new HashMap<>();
            tmp.put("options",JSON.toJSONString(optionsMapList));
            tmp.put("integralVipId",integralVipId);
            vipCustomerLogDao.saveIntegralGoods(tmp);

            Map<String, Object> map = new HashMap<>();
            map.put("status", -2);
            map.put("orderSn", orderSn);
            return map;
        }
    }

    public void addGifts(Integer giftsGrowth, Integer giftsIntegral,String customerId,Integer type,String orgId,String levelId,String vipId) {

        LOGGER.info("addGifts1:giftsGrowth=>"+giftsGrowth+",giftsIntegral=>"+giftsIntegral+",vipId=>"+vipId);

        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customerId,orgId);
        long customerGrowthScore = 0L;
        if(integralCustomerInfo!=null && !StringUtils.isEmpty(integralCustomerInfo.get("customerGrowthScore"))){
            customerGrowthScore = Long.parseLong(integralCustomerInfo.get("customerGrowthScore").toString());
        }
        String actionRemark = "";
        String msg="";
        int otype = 4;
        if(type==1){
            actionRemark="权益卡开通赠送";
            msg="礼包奖励";
        }else {
            actionRemark="用户升级赠送";
            msg="升级奖励";
            otype = 5;
        }
        if(!StringUtils.isEmpty(vipId)){
            int isCoupon = 0;
            if(levelId.equals(vipId)){
                isCoupon = vipCustomerLogDao.getIsCouponLevel(vipId);
            }else{
                isCoupon = vipCustomerLogDao.getIsCoupon(Long.valueOf(vipId));
            }
            if(isCoupon>0){
                try{
                    //TODO 调中台接口送卡券 customerId
                    List<Map<String, Object>> vipCoupons = vipCustomerLogDao.getVipCoupons(vipId);
                    if(vipCoupons != null && vipCoupons.size() > 0){
                        Map<String,Object> param = new HashMap<>();
                        param.put("couponList",vipCoupons);
                        CouponCustomerInfo customerInfo = CouponCustomerInfo
                                .builder()
                                .customerId(customerId)
                                .orgId(orgId)
                                .customerName("")
                                .customerPhone("")
                                .cover("")
                                .sourceUserId("")
                                .build();
                        couponRequest.doRequest("give-coupons", param, customerInfo);
                    }
                }catch (Exception e){
                    LOGGER.error("赠送卡券失败");
                    e.printStackTrace();
                }
            }
        }
        if(giftsIntegral!=null && giftsIntegral>0){
            Map<String, Object> log = new HashMap<String, Object>();
            log.put("logId", UUID.randomUUID().toString());
            log.put("customerId", customerId);
            log.put("scoreValue", giftsIntegral);
            log.put("scoreType", otype);
            log.put("actionRemark", actionRemark+giftsIntegral+"积分");
            vipCustomerLogDao.addIntegral(log);
            this.customerIntegralService.addIntegralCustomerLog(customerId,msg, IntegralEnums.customerScore.toString(),giftsIntegral.toString(),IntegralEnums.other.toString(),orgId);
            stringRedisTemplate.delete("home:customer_info_" + customerId);
        }
        if(giftsGrowth!=null && giftsGrowth>0){
            Map<String, Object> log = new HashMap<String, Object>();
            log.put("logId", UUID.randomUUID().toString());
            log.put("customerId", customerId);
            log.put("growthValue", giftsGrowth);
            log.put("growthType", otype);
            log.put("actionRemark", actionRemark+giftsGrowth+"成长值");
            vipCustomerLogDao.addGrowth(log);
            this.customerIntegralService.addIntegralCustomerLog(customerId,msg, IntegralEnums.customerGrowthScore.toString(),giftsGrowth.toString(),IntegralEnums.other.toString(),orgId);
            stringRedisTemplate.delete("home:customer_info_" + customerId);
            Integer isVip = this.getIsVip(customerId,orgId);
            String globalopenId = vipCustomerLogDao.getGlobalopenIdByCustomerId(customerId);
            if(StringUtils.isEmpty(globalopenId)){
                globalopenId = vipCustomerLogDao.getAppUserIdByCustomerId(customerId);
            }
            String key = MD5.encode(orgId + globalopenId);
            String h5User = stringRedisTemplate.opsForValue().get("login:" + key);
            if(!StringUtils.isEmpty(h5User)){
                WxUser wxUser = JSON.parseObject(h5User, WxUser.class);
                wxUser.setIsVip(isVip);
                h5User = JSON.toJSONString(wxUser);
                stringRedisTemplate.opsForValue().set("login:" + key, h5User, 15, TimeUnit.MINUTES);
            }
        }
        if(giftsGrowth!=null && giftsGrowth>0){
            this.growthOpenAccount(customerId,orgId,customerGrowthScore,vipId);
        }

    }


    public void addLog(VipCustomerLogPo vipLog) {
        vipCustomerLogDao.addLog(vipLog);
    }

    /**
     * 根据权益开通
     */
    public void openBenefit(String benefit,String orgId,String customerId,Integer payMode){
        //更具id查询列表根据type来决定1，2，3
        if(benefit.contains("1")){
            String globalopenId = vipCustomerLogDao.getGlobalopenIdByCustomerId(customerId);
            if(StringUtils.isEmpty(globalopenId)){
                globalopenId = vipCustomerLogDao.getAppUserIdByCustomerId(customerId);
            }
            String key = MD5.encode(orgId + globalopenId);
            String h5User = stringRedisTemplate.opsForValue().get("login:" + key);
            if(!StringUtils.isEmpty(h5User)){
                WxUser wxUser = JSON.parseObject(h5User, WxUser.class);
                wxUser.setIsVip(1);
                h5User = JSON.toJSONString(wxUser);
                stringRedisTemplate.opsForValue().set("login:" + key, h5User, 15, TimeUnit.MINUTES);
            }
            List<String> appUserIdList = vipCustomerLogDao.getappUserIdByCustomerId(customerId);
            if(appUserIdList!=null && appUserIdList.size()>0){
                for(String appUserId : appUserIdList){
                    String appKey = MD5.encode(orgId + appUserId);
                    String appUser = stringRedisTemplate.opsForValue().get("login:" + appKey);
                    if(!StringUtils.isEmpty(appUser)){
                        WxUser wxUser = JSON.parseObject(appUser, WxUser.class);
                        wxUser.setIsVip(1);
                        appUser = JSON.toJSONString(wxUser);
                        stringRedisTemplate.opsForValue().set("login:" + appKey, appUser, 15, TimeUnit.MINUTES);
                    }
                }
            }
        }
        if(benefit.contains("2")){
            //开通联盟商家
            if (merchantSalerService.checkSaler(orgId)) {
                LOGGER.info("达到上限,无法创建");
            }else {
                String pid = "";
                Map<String, Object> salerParam = new HashMap<>();
                salerParam.put("customerId", customerId);
                salerParam.put("pid", pid);
                salerParam.put("joinTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                salerParam.put("payMoney", 0);
                salerParam.put("orgId", orgId);
                salerParam.put("phone", "");
                int count = mallBoomService.getSalerCount(salerParam);
                if (count == 0) {
                    //生成0元订单
                    Map<String, String> ordParam = new HashMap<>();
                    String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
                    ordParam.put("orderSn", orderSn);
                    ordParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    ordParam.put("amount", "0");
                    ordParam.put("pid", pid);
                    ordParam.put("orgId", orgId);
                    ordParam.put("customerId", customerId);
                    ordParam.put("payStatus", "1");
                    ordParam.put("orderType", "saler");
                    ordParam.put("payType", payMode.toString());
                    mallBoomService.addSalerOrder(ordParam);
                    //写入联盟商家数据
                    mallBoomService.addSaler(salerParam);
                    //增加机构联盟商家个数
                    merchantSalerService.addSalerNum(orgId);
                    new Thread(() -> {
                        try {
                            Thread.sleep(1000L);
                            this.getCasUser(customerId);
                        } catch (Exception e) {
                            LOGGER.error("获取小b的cas账号错误", e);
                        }
                    }).start();
                }
            }
        }
        if(benefit.contains("3")) {
            if (merchantSalerService.checkPromoter(orgId)) {
                LOGGER.info("达到上限,无法创建");
            }else {
                Map tmpParam = new HashMap();
                tmpParam.put("orgId", orgId);
                tmpParam.put("customerId", customerId);
                //开通加盟代理
                Map<String, Object> promoterInfo = mallBoomService.getPromoterInfo(tmpParam);
                if (null != promoterInfo) {
                    if (!"promoter".equals(promoterInfo.get("customerType")) && !"1".equals(promoterInfo.get("promoterStatus"))) {
                        if (!merchantSalerService.checkPromoter(orgId)) {
                            Map<String, String> proOrdParam = new HashMap<>();
                            String proOrderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
                            proOrdParam.put("orderSn", proOrderSn);
                            proOrdParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            proOrdParam.put("amount", "0");
                            proOrdParam.put("pid", "");
                            proOrdParam.put("orgId", orgId);
                            proOrdParam.put("customerId", customerId);
                            proOrdParam.put("payStatus", "1");
                            proOrdParam.put("orderType", "promoter");
                            proOrdParam.put("payType", payMode.toString());
                            mallBoomService.addSalerOrder(proOrdParam);
                            mallBoomService.savePromoter(customerId);
                            merchantSalerService.addPromoterNum(orgId);
                        }
                    }
                }
            }
        }
    }

    /**
     * 生成大b账号
     * @param customerId
     * @throws IOException
     * @throws URISyntaxException
     */
    public void getCasUser(String customerId) throws IOException, URISyntaxException {
        Map<String, Object> customerInfo = mallBoomService.getCustomerInfoByCustomerId(customerId);
        if (null == customerInfo) {
            throw GlobalException.build("用户信息不存在");
        }
        String orgId = customerInfo.get("orgId").toString();
        String phone = customerInfo.get("bindPhone").toString();
        String username = customerInfo.get("customerName").toString();
        if(StringUtils.isEmpty(username)){
            username = "手机尾号"+phone.substring(phone.length()-4)+"用户";
        }
        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("orgId", orgId);
        salerParam.put("customerId", customerId);

        Integer salerCount = mallBoomService.getSalerCount(salerParam);//判断该用户是不是小b
        if (salerCount > 0) {
            //生成小b用于登录cas的账号
            String casUserName = "mbl" + phone + orgId;
            String casPassword = getRandom(6);
            Map<String, Object> pushData = new HashMap<>();
            pushData.put("orgcode", orgId);
            pushData.put("account", casUserName);
            pushData.put("username", username);
            pushData.put("pwd", DigestUtils.md5DigestAsHex(casPassword.getBytes()));
            LOGGER.info("pushData===" + JSON.toJSONString(pushData));
            LOGGER.info("url===" + doAddbAccountUrl);
            String postres = httpService.doGet(doAddbAccountUrl + "?action=doAddbAccount", pushData);
            if (null == postres) {
                throw GlobalException.build("验证失败，请重试");
            }
            LOGGER.info("postres===" + postres);
            Map res = (Map) JSON.parse(postres);
            if ((Integer) res.get("RetCode") != 0) {
                switch ((Integer) res.get("RetCode")) {
                    case 3:
                        throw GlobalException.build("你已是麦爆啦店主，请勿重复开通");
                    case 5:
                        throw GlobalException.build("用户达到上限，请联系管理员");
                    default:
                        break;
                }
                throw GlobalException.build("系统繁忙，请稍后再试");
            }
            Map<String, String> params = new HashMap<>();
            params.put("casUserId", res.get("UserID").toString());
            params.put("casUserName", casUserName);
            params.put("casPassword", casPassword);
            params.put("phone", phone);
            params.put("customerId", customerId);
            mallBoomService.savephone(params);
        }
    }

    private static String getRandom(int length) {
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val.append(random.nextInt(10));
        }
        return val.toString();
    }

    /**
     * 计算各类抽成
     */
    private String getSplitItem(Integer sysAmount, String orderSn, String orgId, String note, String merchantFeeAccount,Integer payMode,String shareCustomerId,Long vipId) throws GlobalException {
        Map<String, String> cutPercent = mallBoomService.getOrgCutByOrgId(orgId);

        List<Map<String, Object>> cashSplitItems = new ArrayList<>();
        String linkdrawfeeaccount = this.getCustomerIdByFeeTypeAndOrdId(FeeConstants.LINK_DRAW_FEE, orgId, payMode);
        double v = sysAmount.doubleValue() * Double.valueOf(cutPercent.get("linkerTake")) / 100;
        Integer linkerCut = new BigDecimal(v).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
        if (linkerCut > 0) {
            Map<String, Object> cashSplitItem1 = new HashMap<>();
            cashSplitItem1.put("customerId", linkdrawfeeaccount);
            cashSplitItem1.put("splitAmount", linkerCut);
            cashSplitItem1.put("note", note + "联汇支付抽成");
            cashSplitItem1.put("orderId", orderSn);
            //聯匯抽成不是大B
            cashSplitItem1.put("type",0);
            cashSplitItems.add(cashSplitItem1);
        }

        String orgdrawfeeaccount = this.getCustomerIdByFeeTypeAndOrdId(FeeConstants.ORG_DRAW_FEE, orgId, payMode);
        double u = sysAmount.doubleValue() * Double.valueOf(cutPercent.get("unionbarleyTake")) / 100;
        Integer unionbarleyCut = new BigDecimal(u).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
        if (unionbarleyCut > 0) {
            Map<String, Object> cashSplitItem2 = new HashMap<>();
            cashSplitItem2.put("customerId", orgdrawfeeaccount);
            cashSplitItem2.put("splitAmount", unionbarleyCut);
            cashSplitItem2.put("note", note + "联盟大麦支付抽成");
            cashSplitItem2.put("orderId", orderSn);
            //大麥就是大B
            cashSplitItem2.put("type",1);
            cashSplitItems.add(cashSplitItem2);
        }
        //分佣给分享人
        //TODO 这里是分佣的开通权益卡逻辑
        Integer ratioCut = 0;
        if (!StringUtils.isEmpty(shareCustomerId)) {
            //判断是不是加盟代理
            Integer promoterCount = vipCustomerLogDao.getPromoterCount(shareCustomerId);
            if (promoterCount != null && promoterCount > 0) {
                stringRedisTemplate.opsForValue().set("vipShareCustomerId:" + orderSn, shareCustomerId, 1, TimeUnit.DAYS);
                Integer ratio = vipCustomerLogDao.ratio(vipId);
                if (ratio > 0) {
                    Map<String, Object> cashSplitItem3 = new HashMap<>();
                    double r = sysAmount.doubleValue() * Double.valueOf(ratio) / 100;
                    ratioCut = new BigDecimal(r).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cashSplitItem3.put("customerId", "#yunBizUserId_B2C#");
                    cashSplitItem3.put("splitAmount", ratioCut);
                    cashSplitItem3.put("note", note + "分享佣金");
                    cashSplitItem3.put("orderId", orderSn);
                    //分享人不是大B
                    cashSplitItem3.put("type",0);
                    cashSplitItem3.put("shareCustomerId",shareCustomerId);
                    cashSplitItems.add(cashSplitItem3);
                    stringRedisTemplate.opsForValue().set("vipRatioCut:" + orderSn, JSON.toJSONString(cashSplitItem3), 1, TimeUnit.DAYS);
                }
            }
        }

        Map<String, Object> cashSplitItem4 = new HashMap<>();
        cashSplitItem4.put("customerId", merchantFeeAccount);
        cashSplitItem4.put("splitAmount", sysAmount - linkerCut - unionbarleyCut - ratioCut);
        cashSplitItem4.put("note", note + "商家收益");
        cashSplitItem4.put("orderId", orderSn);
        //商家收益到大B
        cashSplitItem4.put("type",1);
        cashSplitItems.add(cashSplitItem4);
        String cashStr = JSON.toJSONString(cashSplitItems, SerializerFeature.WriteMapNullValue);
        LOGGER.info("cashStr----------------", cashStr);
        return cashStr;
    }

    public Map<String, Object> pay(Integer payMode, String openId, String orderSource, String orgId, Integer amount,String orderSn,String customerId,String frontUrl,String shareCustomerId,Long vipId) {
        if (payMode == 2 || payMode == 3) {
            //app支付
            if ("2".equals(orderSource)) {
                Map<String, Object> resParam = new HashMap<>();
                resParam.put("orderSn", orderSn);
                resParam.put("orderSource", orderSource);
                resParam.put("status", -1);
                return resParam;
            }

            String agentFeeAccount = this.getCustomerIdByFeeTypeAndOrdId(FeeConstants.AGENT_FEE, orgId, payMode);//分账卡号
            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("frontUrl", frontUrl);//支付后跳转前端地址
            reqMap.put("cashAmount", amount);//现金支付金额
            String cashSplitItems = this.getSplitItem(amount, orderSn, orgId, "开通vip", agentFeeAccount, payMode,shareCustomerId,vipId);
            reqMap.put("cashSplitItems", cashSplitItems);//现金分账明细，JSON字符串
            reqMap.put("customerId", customerId);//支付用户ID
            reqMap.put("goodsName", "开通vip");//商品描述
            reqMap.put("openID", openId);//支付用户OPENID
            reqMap.put("orderSn", orderSn);//平台订单ID
            reqMap.put("payeeAccountNumber", agentFeeAccount);//收款用户帐号(收款用户为机构会员时必填，机构结算标识)
            reqMap.put("payeeUserID", purchaseProcessDao.getAccountUidByOrgId(orgId));//收款用户ID
            LOGGER.info("vip---------pay-------reqMap"+JSON.toJSONString(reqMap));
            // 行业代码
            String industryCode = purchaseProcessDao.getOrgMerchantInfoByOrgId(orgId);
            reqMap.put("industryCode", industryCode);
            // 行业名称
            String industryName = purchaseProcessDao.getIndustryNameByCode(industryCode);
            reqMap.put("industryName", industryName);
            // 应用appId
            String appId = "";
            if (payMode == 3) {
                appId = purchaseProcessDao.getAppIdByOrgId("linker");
            }
            if (payMode == 2) {
                appId = purchaseProcessDao.getAppIdByOrgId(orgId);
            }
            reqMap.put("appId", appId);
            String alias = "";
            if (payMode == 3) {
                alias = maiBaoLaService.getAliasByLinker();
            }
            if (payMode == 2) {
                alias = maiBaoLaService.getAlias(orgId);
            }
            reqMap.put("clintType", alias);
            // 支付方式：WX-公众号支付；XCX-微信小程序支付
            reqMap.put("payType", "WX");
            // 访问终端类型:1手机；2PC
            reqMap.put("source", 1);
            // 交易验证方式：0-无验证；1-短信验证码；2-支付密码
            reqMap.put("validateType", 0);



            String result = "";
            String url = wcPayProperties.getAcsurl() + WcPayConstant.TRADE_PAY_ORDER;
            try {
                result = httpService.doPost(url, JSON.toJSONString(reqMap), WcPayConstant.JSON);
                result = this.callResultProcess(result);
            } catch (Exception e) {
                LOGGER.error("支付网关调用异常", e);
                throw GlobalException.build("支付网关调用异常");
            }
            Map res = (Map) JSON.parse(result);
            res.put("orderSn", orderSn);
            res.put("orderSource", orderSource);
            return res;
        } else {
            SortedMap<String, Object> finalpackage = new TreeMap<>();
            Map<String, String> orderParam = new HashMap<>();
//            Long currentTime = new Date().getTime();
            Long currentTime = System.currentTimeMillis();
            String notifyUrl = systemProperties.getScrmUrl() + "/acs/merchantsaler/ordernotify";
            orderParam.put("body", "开通vip");
            orderParam.put("notifyUrl", notifyUrl);
            orderParam.put("openid", openId);
            orderParam.put("outTradeNo", orderSn);
            orderParam.put("timestamp", currentTime.toString());
            orderParam.put("totalFee", amount.toString());
            orderParam.put("tradeType", "JSAPI");
            orderParam.put("wcpayType", "STEPLINK_" + orgId);
            // todo
            if (systemProperties.isWxSplit()) {
                orderParam.put("needShare", "1");
            }
            Map<String, String> appSign = ParamSignUtils.sign(orderParam);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("appSign", appSign.get("appSign")));
            nvps.add(new BasicNameValuePair("notifyUrl", orderParam.get("notifyUrl")));
            nvps.add(new BasicNameValuePair("body", orderParam.get("body")));
            nvps.add(new BasicNameValuePair("outTradeNo", orderParam.get("outTradeNo")));
            nvps.add(new BasicNameValuePair("openid", orderParam.get("openid")));
            nvps.add(new BasicNameValuePair("timestamp", orderParam.get("timestamp")));
            nvps.add(new BasicNameValuePair("totalFee", orderParam.get("totalFee")));
            nvps.add(new BasicNameValuePair("tradeType", orderParam.get("tradeType")));
            nvps.add(new BasicNameValuePair("wcpayType", orderParam.get("wcpayType")));
            if (systemProperties.isWxSplit()) {
                nvps.add(new BasicNameValuePair("needShare", orderParam.get("needShare")));
            }
            String result = ParamSignUtils.callService(payurl + "/pay/wcpay", nvps, 0, 0);
            LOGGER.info("result===[{}]", result);
            Object parse = JSON.parse(result);
            Map ret = (Map) parse;
            if ((Integer) ret.get("rt") != 1) {
                throw GlobalException.build("微信签名失败");
            } else {
                Map retInfo = (Map) ret.get("object");
                finalpackage.put("appId", retInfo.get("appId"));
                finalpackage.put("timeStamp", retInfo.get("timeStamp"));
                finalpackage.put("nonceStr", retInfo.get("nonceStr"));
                finalpackage.put("package", "prepay_id=" + retInfo.get("prepayId"));
                finalpackage.put("signType", retInfo.get("signType"));
                finalpackage.put("paySign", retInfo.get("paySign"));
                finalpackage.put("orderSn", orderSn);
                finalpackage.put("orderSource", orderSource);
            }
            return finalpackage;
        }
    }

    /**
     * 调用结果处理(中金)
     */
    public String callResultProcess(String result) throws GlobalException {
        if (StringUtils.isEmpty(result)) {
            throw GlobalException.build("网关调用失败");
        }
        LOGGER.info(result);
        Map resMap = (Map) com.alibaba.fastjson.JSON.parse(result);
        if (!resMap.containsKey("code")) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        if (!"200".equals(resMap.get("code"))) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        if (!resMap.containsKey("data")) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        Map data = (Map) resMap.get("data");
        if (!data.containsKey("authCode")) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        return (String) data.get("authCode");
    }

    /**
     * 根据机构和费用类型查询分账配置账号id
     *
     * @param type  见FeeConstants
     * @param orgId 机构id
     */
    public String getCustomerIdByFeeTypeAndOrdId(String type, String orgId, Integer payMode) throws GlobalException {
        String account = purchaseProcessDao.getAccountByFeeTypeAndOrdId(type, orgId);
        if (StringUtils.isEmpty(account)) {
            purchaseProcessDao.insertAcsOrgDefaultConfig(orgId);
            account = purchaseProcessDao.getAccountByFeeTypeAndOrdId(type, orgId);
        }
        switch (account) {
            case "A":
                String linkId = "";
                if (payMode == 2) {
                    linkId = purchaseProcessDao.getLinkIdByOrgId(orgId);
                } else if (payMode == 3) {
                    linkId = purchaseProcessDao.getLinkIdByLinkOrg("linker");
                }

                if (StringUtils.isEmpty(linkId)) {
                    throw GlobalException.build("联汇暂未开户");
                }
                return linkId;
            case "B":
                String orgUid = purchaseProcessDao.getAccountUidByOrgId(orgId);
                if (StringUtils.isEmpty(orgUid)) {
                    throw GlobalException.build("机构暂未开户");
                }
                return orgUid;
            case "C":
                // 平台营销资金账户
                return "#yunBizUserId_B2C#";
            default:
                throw GlobalException.build("机构账户配置错误！");
        }
    }

    //app支付，请求签名
    public Object getVipAppPaySign(String orderSn,String openId){
        VipCustomerLogPo vipLogInfo = vipCustomerLogDao.vipLogInfoByOrderSn(orderSn);
        if (null == vipLogInfo) {
            throw GlobalException.build("无此订单！");
        }
        String tit = "开通vip";
        String feeAccount = FeeConstants.VIP_FEE;
        String customerId = vipLogInfo.getCustomerId();
        String orgId = vipLogInfo.getOrgId();
        Integer amount = vipLogInfo.getAmount();
        Integer payMode = vipLogInfo.getPayType();
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("cashAmount", amount);//现金支付金额
        String merchantFeeAccount = this.getCustomerIdByFeeTypeAndOrdId(feeAccount, orgId ,payMode);//分账卡号
        String cashSplitItems = this.getSplitItem(amount, orderSn, orgId, tit, merchantFeeAccount,payMode,"",vipLogInfo.getVipId());
        reqMap.put("cashSplitItems", cashSplitItems);//现金分账明细，JSON字符串
        reqMap.put("customerId", customerId);//支付用户ID
        reqMap.put("goodsName", tit);//商品描述
        reqMap.put("openID", openId);//支付用户OPENID
        reqMap.put("orderSn", orderSn);//平台订单ID
        reqMap.put("payeeAccountNumber", merchantFeeAccount);//收款用户帐号(收款用户为机构会员时必填，机构结算标识)
        reqMap.put("payeeUserID", purchaseProcessDao.getAccountUidByOrgId(orgId));//收款用户ID

        // 行业代码
        String industryCode = purchaseProcessDao.getOrgMerchantInfoByOrgId(orgId);
        reqMap.put("industryCode", industryCode);
        // 行业名称
        String industryName = purchaseProcessDao.getIndustryNameByCode(industryCode);
        reqMap.put("industryName", industryName);
        //应用appId
        String appId = purchaseProcessDao.getXcxAppIdByOrgId(orgId);
        reqMap.put("appId", appId);
        String alias = maiBaoLaService.getAlias(orgId);
        reqMap.put("clintType", alias);
        // 支付方式：WX-公众号支付；XCX-微信小程序支付
        reqMap.put("payType", "XCX");
        // 访问终端类型:1手机；2PC
        reqMap.put("source", 1);
        // 交易验证方式：0-无验证；1-短信验证码；2-支付密码
        reqMap.put("validateType", 0);

        String result = "";
        String url = wcPayProperties.getAcsurl() + WcPayConstant.TRADE_PAY_ORDER;
        try {
            // 积分抵扣为0元
            result = httpService.doPost(url, com.alibaba.fastjson.JSON.toJSONString(reqMap), WcPayConstant.JSON);
            result = this.callResultProcess(result);
        } catch (Exception e) {
            LOGGER.error("支付网关调用异常", e);
            throw GlobalException.build("支付网关调用异常");
        }
        Map res = (Map) JSON.parse(result);
        res.put("orderSn", orderSn);
        res.put("orderSource","2");
        stringRedisTemplate.opsForValue().set("orderType_"+orderSn,"5",1, TimeUnit.HOURS);
        return res;
    }

    public  List<ProtectPo> getRefundData(@Param("orderSn") String orderSn) {
        return vipCustomerLogDao.getRefundData(orderSn);
    }

    public void addRefund(Map<String,Object> param){
        vipCustomerLogDao.addRefund(param);
    }

    public List<ProtectPo> getProtectPoListData(String orderSn) {
        return vipCustomerLogDao.getProtectPoListData(orderSn);
    }

    /**
     *
     * @param customerId
     * @param orgId
     * @param oldGrowthScore 原来的成长值，为null时表示绑手机号动作
     */
    public void growthOpenAccount(String customerId,String orgId,Long oldGrowthScore,String vipId) {
        boolean ifPhone = false;
        Map<String, Object> customerById = vipCustomerLogDao.getCustomerById(customerId);
        if(null != customerById && !StringUtils.isEmpty(customerById.get("bindPhone"))){
            ifPhone = true;
        }
        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customerId,orgId);
        long customerGrowthScore = 0L;
        if(null!=integralCustomerInfo && !StringUtils.isEmpty(integralCustomerInfo.get("customerGrowthScore"))){
            customerGrowthScore = Long.valueOf(integralCustomerInfo.get("customerGrowthScore").toString());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);
        map.put("customerGrowthScore",customerGrowthScore);
        map.put("oldGrowthScore",oldGrowthScore);
        Map<String, Object> customerRight = new HashMap<>();
        List<Map<String, Object>> levels = vipCustomerLogDao.getLevelRightList(map);
        if(null!=levels && levels.size()>0){
            for (Map<String, Object> level : levels) {
                customerRight = level;
                //判断用户是否赠送过(只要是到达就记录，即使以后编辑了（从无到有也不加）)
                String levelId = level.get("levelId").toString();
                int count= vipCustomerLogDao.getGiftsCount(levelId,customerId);
                if(count==0){
                    vipCustomerLogDao.insertGifts(levelId,customerId,orgId);
                    if(null!=oldGrowthScore){
                        //礼包
                        if(!StringUtils.isEmpty(level.get("levelGifts")) || !StringUtils.isEmpty(level.get("levelGrowth")) ){
                            Integer giftsIntegral = 0;
                            if(level.get("levelGifts")!=null){
                                giftsIntegral = Integer.valueOf(level.get("levelGifts").toString());
                            }
                            Integer giftsGrowth = 0;
                            if(level.get("levelGrowth")!=null){
                                giftsGrowth = Integer.valueOf(level.get("levelGrowth").toString());
                            }
                            //礼包
                            if(giftsIntegral>0 || giftsGrowth>0){
                                this.addGifts(giftsGrowth,giftsIntegral,customerId,2,orgId,levelId,vipId);
                            }
                            if(StringUtils.isEmpty(vipId)){
                                this.addGifts(0,0,customerId,2,orgId,levelId,levelId);
                            }
                        }
                    }
                }
            }
            if(ifPhone && !customerRight.isEmpty()){
                List<Map<String, Object>> levelRights = vipCustomerLogDao.levelRight((String) customerRight.get("levelId"));
                for (Map<String, Object> lr : levelRights) {
                    this.openBenefit(lr.get("type").toString(), orgId, customerId, 0);
                }
            }
        }
    }

    public Map<String, Object> getIntegralVipInfo(Map<String, Object> param) {
        Map<String, Object> integralVipInfo = vipCustomerLogDao.getIntegralVipInfo(param);
        if(null == integralVipInfo){
            throw GlobalException.notFound();
        }
        long vipId = Long.valueOf(integralVipInfo.get("originalGoodsId").toString());
        //会员卡-权益
        List<Map<String, Object>> vipRightList = vipCustomerLogDao.getVipRightList(vipId);

        Map<String, Object> vipInfo = vipCustomerLogDao.getVipInfo(vipId,param.get("customerId").toString());
        if(null != vipInfo){

            if("1".equals(vipInfo.get("isCoupon").toString())){
                //权益卡-礼包-卡券
                List<Map<String,Object>> vipCoupons = vipCustomerLogDao.getVipCoupons(String.valueOf(vipId));
                if(null!=vipCoupons && vipCoupons.size()>0){
                    CouponCustomerInfo couponCustomerInfo = CouponCustomerInfo
                            .builder()
                            .customerId(param.get("customerId").toString())
                            .cover("")
                            .customerName("")
                            .orgId(param.get("orgId").toString())
                            .build();
                    for (int i = vipCoupons.size()-1; i >= 0; i--) {
                        Map<String,Object> res = (Map)couponRequest.doRequest("coupon-detail", vipCoupons.get(i), couponCustomerInfo);
                        if(null == res || null == res.get("name")){
                            vipCoupons.remove(i);
                        }else{
                            vipCoupons.get(i).put("name", res.get("name"));
                            vipCoupons.get(i).put("cover",res.get("cover"));
                        }
                    }
                }
                vipInfo.put("vipCouponList",vipCoupons);
            }else{
                vipInfo.put("vipCouponList",new ArrayList<>());
            }
            vipInfo.put("vipRightList",vipRightList);
            vipInfo.put("options",integralVipInfo.get("options"));
            vipInfo.put("quotaLevel",integralVipInfo.get("quotaLevel"));
            vipInfo.put("goodsCount",integralVipInfo.get("goodsCount"));
            vipInfo.put("originalGoodsId",integralVipInfo.get("originalGoodsId"));
            param.put("vipId",vipId);
            VipPo vipInfo2 = vipCustomerLogDao.vipInfoByOpen(param);
            if (null != vipInfo2) {
                Integer effectiveType = vipInfo2.getEffectiveType();
                if (StringUtils.isEmpty(vipInfo2.getExpireDay()) || effectiveType == 1) {
                    vipInfo.put("expireDay","永久");
                } else {
                    vipInfo.put("expireDay",vipInfo2.getExpireDay());
                }
                vipInfo.put("cardId",vipInfo2.getCardId());
            }else{
                vipInfo.put("cardId",null);
                vipInfo.put("expireDay",null);
            }
            if(!StringUtils.isEmpty(integralVipInfo.get("quotaVips"))){
                List<Map> vipList = vipCustomerLogDao.getQuotaVipList(integralVipInfo.get("quotaVips").toString(),param.get("customerId").toString());
                vipInfo.put("quotaVipList",vipList);
            }
            return vipInfo;
        }else{
            throw GlobalException.notFound();
        }
    }

    public PageInfo getVipCoupon(String customerId,String orgId,Integer pageIndex,Integer pageSize) {
        CouponCustomerInfo couponCustomerInfo = CouponCustomerInfo
                .builder()
                .customerId(orgId)
                .cover("")
                .customerName("")
                .orgId(orgId)
                .build();
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String,Object>> list = vipCustomerLogDao.getVipCoupon(customerId);
        for(Map<String,Object> da:list){
            da.put("vipVo",null);
            da.put("couponVo",null);
            String id = da.get("couponId").toString();
            if(id.length() == 36){
                //卡券
                List<String> consumptionIds = new ArrayList<>();
                consumptionIds.add(id);
                Map<String, Object> param = new HashMap<>();
                param.put("couponIds", consumptionIds);
                param.put("useScene", -1);
                Object result = couponRequest.doRequest("customer-goods-coupon", param, couponCustomerInfo);
                List<JSONObject> resList = (List<JSONObject>) result;
                if(null!=resList && resList.size()>0){
                    for(JSONObject jo:resList){
                        CustomerCouponVo customerCouponVo = JSON.toJavaObject(jo, CustomerCouponVo.class);
                        if(customerCouponVo.getCouponId().equals(id)){
                            da.put("couponVo",customerCouponVo);
                        }
                    }
                }
            }else{
                //权益卡
                Map<String,Object> vipBaseInfo = vipCustomerLogDao.getVipBaseInfo(id);
                da.put("vipVo",vipBaseInfo);
            }
        }
        vipCustomerLogDao.setIsRead(customerId);
        return new PageInfo<>(list);
    }
}
